package com.Beans.Dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.Beans.Models.Solicitud;
import com.Beans.Models.Trakingestados;
import com.Beans.Dao.HibernateUtil;

public class TrakingestadosDAO {

	public static void persistActivo(Trakingestados t){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.persist(t);
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
	public static Trakingestados findByIdSolicitud(Solicitud solicitud){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		Trakingestados te = null;
		try{
			tr = session.beginTransaction();
			Query q = session.createQuery("FROM Trakingestados te WHERE te.solicitud = :solicitud");
			q.setParameter("solicitud", solicitud);
			te = (Trakingestados)q.uniqueResult();
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return te;
	}
	
	public static List<Trakingestados> findByEmployee(int empleado_id){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		List <Trakingestados> tes = null;
		try{
			tr = session.beginTransaction();
			Query q = session.createQuery("SELECT te FROM Trakingestados te, Solicitud s WHERE te.solicitud = s AND te.idEmpleado = :IdEmpleado ORDER BY s.fechaEmision DESC");
			q.setParameter("IdEmpleado", empleado_id);
			tes = (List<Trakingestados>)q.list();
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return tes;
	}
	
	public static List<Trakingestados> findByArea(int area_destino){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		List <Trakingestados> tes = null;
		try{
			tr = session.beginTransaction();
			Query q = session.createQuery("SELECT te FROM Trakingestados te, Solicitud s WHERE te.solicitud = s AND s.idAreaDestino = :area_destino ORDER BY s.fechaEmision DESC");
			q.setParameter("area_destino", area_destino);
			tes = (List<Trakingestados>)q.list();
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return tes;
	}
	
	public static void update(Trakingestados te){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr =null;
		try{
			tr = session.beginTransaction();
			session.update(te);
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
	
}
